// 配置相关功能模块
import { showError } from './resultHandler.js';

/**
 * 从服务器加载配置
 * @returns {Promise<Object>} 配置对象
 */
export async function loadConfig() {
    try {
        const response = await fetch('/api/config');
        const config = await response.json();
        
        document.getElementById('apiKey').value = config.deepseek_api_key || '';
        document.getElementById('apiUrl').value = config.deepseek_api_url || '';
        
        const stockSymbols = config.stock_symbols || [];
        document.getElementById('stockSymbols').value = stockSymbols.join(', ');
        document.getElementById('lookbackDays').value = config.lookback_days || 60;
        
        return config;
    } catch (error) {
        console.error('加载配置失败:', error);
        showError('加载配置失败');
        return {};
    }
}

/**
 * 保存配置到服务器
 * @param {Object} config 配置对象
 * @returns {Promise<boolean>} 是否保存成功
 */
export async function saveConfig(config) {
    try {
        const response = await fetch('/api/config', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(config)
        });
        
        return response.ok;
    } catch (error) {
        console.error('保存配置失败:', error);
        return false;
    }
}

/**
 * 显示配置模态框
 */
export function showConfigModal() {
    loadConfig().then(() => {
        document.getElementById('configModal').classList.remove('hidden');
    });
}

/**
 * 隐藏配置模态框
 */
export function hideConfigModal() {
    document.getElementById('configModal').classList.add('hidden');
}

/**
 * 处理配置表单提交
 * @param {Event} e 表单提交事件
 */
export function handleConfigSubmit(e) {
    e.preventDefault();
    
    const symbolsInput = document.getElementById('stockSymbols').value;
    const symbolsArray = symbolsInput.split(',');
    const trimmedSymbols = symbolsArray
        .map(symbol => symbol.trim())
        .filter(symbol => symbol);
    
    const config = {
        deepseek_api_key: document.getElementById('apiKey').value,
        deepseek_api_url: document.getElementById('apiUrl').value,
        stock_symbols: trimmedSymbols,
        lookback_days: parseInt(document.getElementById('lookbackDays').value) || 60
    };
    
    saveConfig(config).then(success => {
        if (success) {
            alert('配置保存成功！');
            hideConfigModal();
        } else {
            showError('配置保存失败！');
        }
    });
}